package com.bc004346.travelus.adapter;

import android.app.Activity;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.TextView;

import com.bc004346.travelus.R;
import com.bc004346.travelus.model.domain.Passenger;
import com.bc004346.travelus.model.interfaces.ISelectPassengerListener;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by Renats on 4/1/2014.
 * custom passenger display
 */
public class PassengerAdapter extends BaseAdapter {

    private static LayoutInflater mInflater = null;
    private List<Passenger> mPassengers = new ArrayList<Passenger>();
    private ISelectPassengerListener mActivity;
    private CompoundButton mButton;

    public PassengerAdapter(Activity activity, List<Passenger> p) {
        mPassengers = p;
        mInflater = (LayoutInflater) activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        mActivity = (ISelectPassengerListener) activity;
    }

    public void deselectPassenger(Passenger pax) {
        pax.setSelected(!pax.isSelected());
        mButton.setChecked(!mButton.isChecked());
    }

    @Override
    public int getCount() {
        return mPassengers.size();
    }

    @Override
    public Object getItem(int position) {
        return position;
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {

        View view = convertView;

        if (convertView == null)
            view = mInflater.inflate(R.layout.list_passenger, null);

        if (view != null) {
            TextView name = (TextView) view.findViewById(R.id.list_passenger_name);
            final CheckBox isSelected = (CheckBox) view.findViewById(R.id.list_passenger_isSelected);
            final Passenger pax = mPassengers.get(position);

            name.setText(pax.getName());

            isSelected.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
                @Override
                public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                    mButton = buttonView;
                    pax.setSelected(isChecked);
                    mActivity.selectPassenger(pax);
                }
            });

            view.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    isSelected.setChecked(!isSelected.isChecked());
                }
            });
        }

        return view;
    }
}
